package org.linphone.sub.sublist;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.xuhao.android.libsocket.sdk.ConnectionInfo;
import com.xuhao.android.libsocket.sdk.OkSocket;
import com.xuhao.android.libsocket.sdk.OkSocketOptions;
import com.xuhao.android.libsocket.sdk.SocketActionAdapter;
import com.xuhao.android.libsocket.sdk.bean.OriginalData;
import com.xuhao.android.libsocket.sdk.connection.IConnectionManager;
import com.xuhao.android.libsocket.sdk.protocol.IHeaderProtocol;

import org.linphone.http.HtmlService;
import org.linphone.sub.audio.AudioCapturer;
import org.linphone.sub.audio.AudioPlay;
import org.linphone.sub.bean.SubConf;
import org.linphone.sub.send.SendBroadData;
import org.linphone.sub.send.SendStartBroadData;
import org.linphone.sub.send.SendStateData;
import org.linphone.sub.send.SendStopBroadData;
import org.linphone.sub.utils.ArrayUtil;
import org.linphone.sub.utils.CRCUtil;
import org.linphone.sub.utils.FileUtil;
import org.linphone.sub.utils.SocketUtil;
import org.linphone.sub.utils.StateUtil;
import org.linphone.sub.utils.UpdateUtil;
import org.linphone.sub.utils.VolumeUtil;
import org.linphone.utils.SpUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Objects;

/**
 * Created by Xiang on 2018/5/15.
 */

public class ListPresenter implements IListPresenter {

	//展示界面的View
	private IListView mView;
	//log日志打印的标签
	private String TAG = "ListPresenter";
	//配置信息的服务
	private Intent httpService;
	//广播服务端IP
	private String ip;
	//广播服务端端口
	private String port;
	//分站实体类
	private SubConf sc = SubConf.getmInstance();
	//音频播放类
	private AudioPlay mAudioPlay;
	//音频录音类
	private AudioCapturer mAudioCapture;
	//音乐播放器
	private MediaPlayer mediaPlayer;
	//Socket连接管理者
	private IConnectionManager manager;
	//从服务器接收到的每条数据
	private byte[] bb;
	//本地广播管理者
	private LocalBroadcastManager localBroadcastManager;
	//服务端广播开启
	private static final String BROADCAST_SERVER = "com.sxygsj.broadcast.server";
	//客户端广播开启
	private static final String BROADCAST_CLIENT = "com.sxygsj.broadcast.client";
	//准备开启服务端广播
	private static final String PHONE_SERVER_START = "com.sxygsj.phone.server.start";
	//准备开启客户端广播
	private static final String PHONE_CLIENT_START = "com.sxygsj.phone.client.start";
	//广播停止
	private static final String PHONE_STOP = "com.sxygsj.phone.stop";
	//sip广播接收者
	private SipBroadcastReceiver sipBroadcastReceiver = new SipBroadcastReceiver();

	//当前收到的音乐名称
	private String mMusicName;
	//当前的背景音乐文件名称集合
	private static ArrayList<String> musicList = new ArrayList<String>();
	//当前播放的背景音乐文件索引
	private int songIndex = 0;
	//构造参数
	ListPresenter(IListView view){
		mView = view;
	}

	//初始化数据
	@Override
	public void start(SubListActivity ctx) {
		ip = SpUtil.getString(ctx, "serverIP", "192.168.14.10");
		port = SpUtil.getString(ctx, "serverPort", "1717");
		Log.i(TAG, "socketConnect: " + ip + ".........." + port);
		startServer(ctx);//andserver注册sip号与广播地址;
		localBroadcastManager = LocalBroadcastManager.getInstance(ctx);
		initAudio(ctx.getBaseContext());
		registerLoginBroadcast();//在SublistActivity中进行调用后,对SIP电话进行处理,在CallIncomingActivity与CallOutcomingActivity中进行发送广播
		if(manager==null){
			Log.i(TAG, "start: ------------------------------1");
			if(musicList!=null && musicList.size()>0){
				for(int i=0;i<musicList.size();i++){
					FileUtil.deletefile(musicList.get(i));
				}
				musicList.clear();
				mMusicName = "";
			}
			socketConnect(ctx);
		}else{
			if(!manager.isConnect()){
				manager.connect();
			}
		}

		UpdateUtil up = new UpdateUtil(ctx);
		up.setmOnUpdateListener(new UpdateUtil.OnUpdateListener() {
			@Override
			public void onUpdate() {
				for(int i=0;i<musicList.size();i++){
					FileUtil.deletefile(musicList.get(i));
				}
			}
		});
		up.checkVersion();
	}

	//开启配置信息服务,andserver
	private void startServer(Context ctx) {
		httpService = new Intent(ctx,HtmlService.class);
		ctx.startService(httpService);
	}

	//初始化音频数据
	private void initAudio(Context baseContext) {

		mAudioCapture = new AudioCapturer();
		mAudioPlay = new AudioPlay();

		mediaPlayer = new MediaPlayer();
		mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
			@Override
			public void onCompletion(MediaPlayer mp) {
				nextSong();
			}
		});
	}

	//播放下一首歌曲
	private void nextSong() {
		if(songIndex<musicList.size()-1){
			songIndex = songIndex +1;
			songPlay();
		}else {
			songIndex = 0;
			songPlay();
		}

	}

	//背景音乐播放
	private void songPlay() {
		if(musicList.size()==0){
			return;
		}

		File ff = new File(Environment.getExternalStorageDirectory(), musicList.get(songIndex));

		try {
			FileInputStream fis = new FileInputStream(ff);
			mediaPlayer.reset();
			mediaPlayer.setDataSource(fis.getFD());
			mediaPlayer.prepare();
			mediaPlayer.start();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * sip广播接收者,在注册时发送广播并处理,
	 * 主要作用,有广播的时候关闭视频,一切以广播为优先*/
	private class SipBroadcastReceiver extends BroadcastReceiver {

		@RequiresApi(api = Build.VERSION_CODES.KITKAT)
		@Override
		public void onReceive(Context context, Intent intent) {
			if(Objects.equals(intent.getAction(), PHONE_SERVER_START)){
				if(mediaPlayer.isPlaying()){
					mediaPlayer.pause();
					mediaPlayer.stop();
				}
				if(mAudioCapture.isCaptureStarted()){
					mAudioCapture.stopCapture();
				}
				if(mAudioPlay!=null){
					mAudioPlay.stopPlayer();
				}

				SubListActivity.STATE_NUM = 5;//主控分站通话
				Log.i(TAG, "onReceive:hahahhahahah "+SubListActivity.STATE_NUM);
				manager.send(new SendStateData(SubListActivity.STATE_NUM));

			}else if(Objects.equals(intent.getAction(), PHONE_CLIENT_START)){
				if(mediaPlayer.isPlaying()){
					mediaPlayer.pause();
					mediaPlayer.stop();
				}

				SubListActivity.STATE_NUM = 3;
				Log.i(TAG, "onReceive:hahahhahahah "+SubListActivity.STATE_NUM);
				manager.send(new SendStateData(SubListActivity.STATE_NUM));

			}else if(Objects.equals(intent.getAction(), PHONE_STOP)){
				SubListActivity.STATE_NUM = 1;
				manager.send(new SendStateData(SubListActivity.STATE_NUM));
			}
		}
	}

	//注册广播方法
	private void registerLoginBroadcast(){
		IntentFilter intentFilter = new IntentFilter(PHONE_SERVER_START);
		intentFilter.addAction(PHONE_CLIENT_START);
		intentFilter.addAction(PHONE_STOP);
		localBroadcastManager.registerReceiver(sipBroadcastReceiver,intentFilter);
	}

	//取消注册
	private void unRegisterLoginBroadcast(){
		if(sipBroadcastReceiver!= null){
			localBroadcastManager.unregisterReceiver(sipBroadcastReceiver);
		}
	}

	// 模拟键盘按键，Keycode对应Android键盘按键的的keycode
	public void setKeyPress(int keycode){
		try
		{
			String keyCommand = "input keyevent " + keycode;
			Runtime runtime = Runtime.getRuntime();
			Process proc = runtime.exec(keyCommand);
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	//获取分站信息数据
	@Override
	public void getSubConf() {
		SubConf sc = SubConf.getmInstance();
		sc.notifyDataSetChange();
	}

	//界面销毁
	@Override
	public void destroy(SubListActivity ctx) {
		mView = null;
		mediaPlayer.release();
		mediaPlayer = null;
		for(int i=0;i<musicList.size();i++){
			FileUtil.deletefile(musicList.get(i));
		}
		musicList.clear();

		if(mAudioPlay!=null){
			mAudioPlay.stopPlayer();
		}
		if(mAudioCapture!=null){
			mAudioCapture.stopCapture();
		}
		if(httpService!=null){
			ctx.stopService(httpService);
		}

//		if(mReceiver!=null){
//			mReceiver.unRegister();
//		}
		unRegisterLoginBroadcast();
	}

	//分站广播发送数据
	@Override
	public void startBroadcast(ArrayList<String> alIp, final ArrayList<String> alState) {
		//audioPlayerHandler.stop();
		if(mediaPlayer.isPlaying()){
			mediaPlayer.pause();
			mediaPlayer.stop();
		}

		final ArrayList<String> al = new ArrayList<>();
		for(int i=0;i<alState.size();i++){
			//TODO  测试离线也传数据 上线时需调整去掉下行的=
			if(StateUtil.stringToInt(alState.get(i))<4 && StateUtil.stringToInt(alState.get(i))>=0 ){
				al.add(alIp.get(i));
			}
		}
		manager.send(new SendStartBroadData());

		SubListActivity.STATE_NUM = 4;
		Log.i(TAG, "startBroadcast: .......................");
		manager.send(new SendStateData(SubListActivity.STATE_NUM));

		mAudioCapture.startCapture();
		mAudioCapture.setOnAudioFrameCapturedListener(new AudioCapturer.OnAudioFrameCapturedListener() {
			@Override
			public void onAudioFrameCaptured(byte[] audioData) {
				Log.i(TAG, "onAudioFrameCaptured: "+audioData.length);
				manager.send(new SendBroadData(audioData,al));//发送自己的数据到服务器
			}
		});

	}

	//停止分站广播
	@Override
	public void stopBroadcast() {
		mAudioCapture.stopCapture();
		manager.send(new SendStopBroadData());
		SubListActivity.STATE_NUM = 1;
		manager.send(new SendStateData(SubListActivity.STATE_NUM));
		//audioRecoderHandler.stoppRecord();
	}

	//与广播服务端通过Socket通信
	private void socketConnect(final SubListActivity ctx) {
		//连接参数设置(IP,端口号),这也是一个连接的唯一标识,不同连接,该参数中的两个值至少有其一不一样
		ConnectionInfo info = new ConnectionInfo(ip, Integer.parseInt(port));
		//调用OkSocket,开启这次连接的通道,调用通道的连接方法进行连接.
		OkSocketOptions options= OkSocketOptions.getDefault();

		//基于当前参配对象构建一个参配建造者类
		OkSocketOptions.Builder builder = new OkSocketOptions.Builder(options);
		//修改参配设置
		builder.setSinglePackageBytes(40960);
		builder.setReadSingleTimeBufferBytes(40960);
		//builder.setReconnectionManager(new NoneReconnect());
		builder.setHeaderProtocol(new IHeaderProtocol() {
			@Override
			public int getHeaderLength() {
				return 4;
			}

			@Override
			public int getBodyLength(byte[] header, ByteOrder byteOrder) {

				return ArrayUtil.bytesToIntBig2(header,0);


			}
		});
		manager = OkSocket.open(info,builder.build());

		manager.registerReceiver(new SocketActionAdapter() {
			@Override
			public void onSocketDisconnection(Context context, ConnectionInfo info, String action, Exception e) {
				//super.onSocketDisconnection(context, info, action, e);
				for(int i=0;i<musicList.size();i++){
					FileUtil.deletefile(musicList.get(i));
				}
				musicList.clear();
				mMusicName = "";
				if(mediaPlayer.isPlaying()){
					mediaPlayer.pause();
					mediaPlayer.stop();
				}
			}

			@Override
			public void onSocketConnectionSuccess(Context context, ConnectionInfo info, String action) {
				Log.i(TAG, "onSocketConnectionSuccess: 连接成功");
				//发送分站状态信息
				SubListActivity.STATE_NUM = 1;//连接成功
				manager.send(new SendStateData(SubListActivity.STATE_NUM));
				super.onSocketConnectionSuccess(context, info, action);

				//连接广播服务器成功时跳转到sip电话界面，测试用
//				Intent intent = new Intent(ctx, LinphoneActivity.class);
//				ctx.startActivity(intent);
			}

			@Override
			public void onSocketConnectionFailed(Context context, ConnectionInfo info, String action, Exception e) {
				Log.i(TAG, "onSocketDi8sconnection: 链接失败");
				for(int i=0;i<musicList.size();i++){
					FileUtil.deletefile(musicList.get(i));
				}
				musicList.clear();
				mMusicName = "";
				if(mediaPlayer.isPlaying()){
					mediaPlayer.pause();
					mediaPlayer.stop();
				}
				super.onSocketConnectionFailed(context, info, action, e);
				//连接广播服务器失败时跳转到sip电话界面，测试用
//				Intent intent = new Intent(ctx, LinphoneActivity.class);
//				ctx.startActivity(intent);
			}

			//从广播服务端读取数据
			@Override
			public void onSocketReadResponse(Context context, ConnectionInfo info, String action, OriginalData data) {
				bb = data.getBodyBytes();
				//根据与服务端的协议解析数据
				if (SocketUtil.byteToHexString(bb[0]).equals("fb")//开始
						&& SocketUtil.byteToHexString(bb[bb.length - 3]).equals("fd")//结束
						&& CRCUtil.crc16(bb)) {
					//验证通过获得一条完整数据后通过功能代码执行不同的工作
					if (SocketUtil.byteToHexString(bb[1]).equals("c1")) {//分站信息
						Log.i(TAG, "onSocketReadResponse: C111111111111");
						String numStr = String.valueOf(SocketUtil.byteToInt(bb[14 + SocketUtil.byteToInt(bb[11])]));
						String className = SocketUtil.unicode2String(SocketUtil.bytesToHexString(bb,
								16 + SocketUtil.byteToInt(bb[11]), bb.length - 4));
						String subNum = String.valueOf(SocketUtil.byteToInt(bb[7])) + "." +
								String.valueOf(SocketUtil.byteToInt(bb[8])) + "." +
								String.valueOf(SocketUtil.byteToInt(bb[9])) + "." +
								String.valueOf(SocketUtil.byteToInt(bb[10]));
						String subName = SocketUtil.unicode2String(SocketUtil.bytesToHexString(bb, 12, 11 + SocketUtil.byteToInt(bb[11])));
						int subSip = SocketUtil.bytesToInt2(bb[12 + SocketUtil.byteToInt(bb[11])], bb[13 + SocketUtil.byteToInt(bb[11])]);
						//boolean isHasIp = false;
						if (sc != null && sc.getSubgrouplist() != null) {
							for (SubConf.SubgroupConf ss : sc.getSubgrouplist()) {
								if (ss.getSublist() != null) {
									for (SubConf.SubgroupConf.SubListConf sss : ss.getSublist()) {
										if (sss.getIp().equals(subNum)) {
											//isHasIp = true;
											return;
										}
									}
								}

							}
							//Log.i(TAG, "onSocketReadResponse: "+isHasIp);
						}

						//if(!isHasIp){
						if (!subNum.equals(SocketUtil.getHostIp())) {
							if (!sc.getSubClassList().isEmpty() && sc.getSubClassList().contains(numStr)) {
								Log.i(TAG, "run: " + "加入原来的组");
								for (SubConf.SubgroupConf ss : sc.getSubgrouplist()) {
									if (ss.getNumber().equals(numStr)) {
										SubConf.SubgroupConf.SubListConf sss = new SubConf.SubgroupConf.SubListConf();
										sss.setSip(subSip);
										sss.setStates(StateUtil.intToString("00"));
										sss.setIp(subNum);
										sss.setName(subName);
										ss.getSublist().add(sss);
										break;
									}
								}
							} else {
								Log.i(TAG, "run: 新建组。。。");
								ArrayList<SubConf.SubgroupConf.SubListConf> asss = new ArrayList<>();
								ArrayList<SubConf.SubgroupConf> ass = new ArrayList<>();
								SubConf.SubgroupConf ss = new SubConf.SubgroupConf();
								SubConf.SubgroupConf.SubListConf sss = new SubConf.SubgroupConf.SubListConf();
								sss.setSip(subSip);
								sss.setStates(StateUtil.intToString("00"));
								sss.setIp(subNum);
								sss.setName(subName);
								ss.setName(className);
								ss.setNumber(numStr);
								asss.add(sss);
								ss.setSublist(asss);

								if (sc.getSubgrouplist() != null && sc.getSubgrouplist().size() > 0) {
									sc.getSubgrouplist().add(ss);

								} else {
									ass.add(ss);
									sc.setSubgrouplist(ass);

								}
							}
						} else {
							Log.i(TAG, "run: 本机ip" + subNum);
						}

						sc.notifyDataSetChange();
						//}
					} else if (SocketUtil.byteToHexString(bb[1]).equals("c6")) {
						Log.i(TAG, "onSocketReadResponse: C666");
						String numStr = String.valueOf(SocketUtil.byteToInt(bb[14 + SocketUtil.byteToInt(bb[11])]));
						String className = SocketUtil.unicode2String(SocketUtil.bytesToHexString(bb,
								16 + SocketUtil.byteToInt(bb[11]), bb.length - 4));
						String subNum = String.valueOf(SocketUtil.byteToInt(bb[7])) + "." +
								String.valueOf(SocketUtil.byteToInt(bb[8])) + "." +
								String.valueOf(SocketUtil.byteToInt(bb[9])) + "." +
								String.valueOf(SocketUtil.byteToInt(bb[10]));
						String subName = SocketUtil.unicode2String(SocketUtil.bytesToHexString(bb, 12, 11 + SocketUtil.byteToInt(bb[11])));
						int subSip = SocketUtil.bytesToInt2(bb[12 + SocketUtil.byteToInt(bb[11])], bb[13 + SocketUtil.byteToInt(bb[11])]);
						boolean isHasIp = false;
						if (!subNum.equals(SocketUtil.getHostIp())) {
							Log.i(TAG, "run: " + "修改信息");
							SubConf.SubgroupConf.SubListConf ssss = new SubConf.SubgroupConf.SubListConf();
							aa:
							for (SubConf.SubgroupConf ss : sc.getSubgrouplist()) {

								for (SubConf.SubgroupConf.SubListConf sss : ss.getSublist()) {
									if (sss.getIp().equals(subNum)) {
										isHasIp = true;
										if (ss.getNumber().equals(numStr)) {
											sss.setSip(subSip);
											sss.setStates(StateUtil.intToString("00"));
											sss.setName(subName);
										} else {
											ss.getSublist().remove(sss);
											ssss.setIp(subNum);
											ssss.setSip(subSip);
											ssss.setStates(StateUtil.intToString("00"));
											ssss.setName(subName);
											if (!sc.getSubClassList().isEmpty() && sc.getSubClassList().contains(numStr)) {
												for (SubConf.SubgroupConf ssb : sc.getSubgrouplist()) {
													if (ssb.getNumber().equals(numStr)) {
														ssb.getSublist().add(ssss);
														break;
													}
												}
											} else {
												ArrayList<SubConf.SubgroupConf.SubListConf> asss = new ArrayList<>();
												ArrayList<SubConf.SubgroupConf> ass = new ArrayList<>();
												SubConf.SubgroupConf ssc = new SubConf.SubgroupConf();

												ssc.setName(className);
												ssc.setNumber(numStr);
												asss.add(ssss);
												ssc.setSublist(asss);

												if (sc.getSubgrouplist() != null && sc.getSubgrouplist().size() > 0) {
													sc.getSubgrouplist().add(ssc);

												} else {
													ass.add(ssc);
													sc.setSubgrouplist(ass);
												}


											}

										}
										break aa;
									}
								}
							}

							if (!isHasIp) {
								if (!sc.getSubClassList().isEmpty() && sc.getSubClassList().contains(numStr)) {
									Log.i(TAG, "run: " + "加入原来的组");
									for (SubConf.SubgroupConf ss : sc.getSubgrouplist()) {
										if (ss.getNumber().equals(numStr)) {
											SubConf.SubgroupConf.SubListConf sss = new SubConf.SubgroupConf.SubListConf();
											sss.setSip(subSip);
											sss.setStates(StateUtil.intToString("00"));
											sss.setIp(subNum);
											sss.setName(subName);
											ss.getSublist().add(sss);
											break;
										}
									}
								} else {
									Log.i(TAG, "run: 新建组。。。");
									ArrayList<SubConf.SubgroupConf.SubListConf> asss = new ArrayList<>();
									ArrayList<SubConf.SubgroupConf> ass = new ArrayList<>();
									SubConf.SubgroupConf ss = new SubConf.SubgroupConf();
									SubConf.SubgroupConf.SubListConf sss = new SubConf.SubgroupConf.SubListConf();
									sss.setSip(subSip);
									sss.setStates(StateUtil.intToString("00"));
									sss.setIp(subNum);
									sss.setName(subName);
									ss.setName(className);
									ss.setNumber(numStr);
									asss.add(sss);
									ss.setSublist(asss);

									if (sc.getSubgrouplist() != null && sc.getSubgrouplist().size() > 0) {
										sc.getSubgrouplist().add(ss);

									} else {
										ass.add(ss);
										sc.setSubgrouplist(ass);

									}
								}
							}
							sc.notifyDataSetChange();
						} else {
							Log.i(TAG, "run: 本机ip" + subNum);
						}
					} else if (SocketUtil.byteToHexString(bb[1]).equals("c2")) {//单分站状态
						//分站状态
						Log.i(TAG, "onSocketReadResponse: C222");
						String subSIP = String.valueOf(SocketUtil.byteToInt(bb[7])) + "." +
								String.valueOf(SocketUtil.byteToInt(bb[8])) + "." +
								String.valueOf(SocketUtil.byteToInt(bb[9])) + "." +
								String.valueOf(SocketUtil.byteToInt(bb[10]));
						String states = String.valueOf(SocketUtil.byteToInt(bb[11]));
						if (!subSIP.equals(SocketUtil.getHostIp())) {
							for (SubConf.SubgroupConf ss : sc.getSubgrouplist()) {

								for (SubConf.SubgroupConf.SubListConf sss : ss.getSublist()) {
									if (sss.getIp().equals(subSIP)) {
										sss.setStates(StateUtil.intToString(states));
										sc.notifyDataSetChange();
									}
								}
							}

						}

					} else if (SocketUtil.byteToHexString(bb[1]).equals("c7")) {//删除分站

						Log.i(TAG, "onSocketReadResponse: C777");
						String subSIP = String.valueOf(SocketUtil.byteToInt(bb[7])) + "." +
								String.valueOf(SocketUtil.byteToInt(bb[8])) + "." +
								String.valueOf(SocketUtil.byteToInt(bb[9])) + "." +
								String.valueOf(SocketUtil.byteToInt(bb[10]));
						if (!subSIP.equals(SocketUtil.getHostIp())) {
							for (SubConf.SubgroupConf ss : sc.getSubgrouplist()) {

								for (SubConf.SubgroupConf.SubListConf sss : ss.getSublist()) {
									if (sss.getIp().equals(subSIP)) {
										ss.getSublist().remove(sss);
									}
								}
							}
							sc.notifyDataSetChange();
						}
					} else if (SocketUtil.byteToHexString(bb[1]).equals("ca")) {//背景音乐文件名

						Log.i(TAG, "onSocketReadResponse: Caaa");
						String musicName = SocketUtil.unicode2String(SocketUtil.bytesToHexString(bb,
								8, bb.length - 4));
						Log.i(TAG, "onSocketReadResponse: " + musicName);
						if (musicList.contains(musicName)) {

							FileUtil.deletefile(musicName);
							musicList.remove(musicName);
						}
						mMusicName = musicName;
						musicList.add(musicName);

					} else if (SocketUtil.byteToHexString(bb[1]).equals("cb")) {//开始播放背景音乐

						Log.i(TAG, "onSocketReadResponse: Cbbb");
						if (SubListActivity.STATE_NUM != 2) {
							SubListActivity.STATE_NUM = 2;//背景音乐
							manager.send(new SendStateData(SubListActivity.STATE_NUM));
							songPlay();
						}

					} else if (SocketUtil.byteToHexString(bb[1]).equals("cc")) {//停止播放背景音乐

						Log.i(TAG, "onSocketReadResponse: Cccc");
						if (SubListActivity.STATE_NUM != 1) {
							SubListActivity.STATE_NUM = 1;//空闲
							manager.send(new SendStateData(SubListActivity.STATE_NUM));
							mediaPlayer.pause();
							mediaPlayer.stop();
							//mediaPlayer.release();
						}
					} else if (SocketUtil.byteToHexString(bb[1]).equals("cd")) {//停止实时服务语音广播

						Log.i(TAG, "onSocketReadResponse: Cddd");
						//setKeyPress(KeyEvent.KEYCODE_F5);
						if (SubListActivity.STATE_NUM != 1) {
							SubListActivity.STATE_NUM = 1;//空闲
							manager.send(new SendStateData(SubListActivity.STATE_NUM));
							mAudioPlay.stopPlayer();
						}

					} else if (SocketUtil.byteToHexString(bb[1]).equals("ce")) {
						//停止实时分站语音广播
						Log.i(TAG, "onSocketReadResponse: Ceee");
						//setKeyPress(KeyEvent.KEYCODE_F5);
						if (mAudioCapture.isCaptureStarted()) {
							mAudioCapture.stopCapture();
						}
						if (SubListActivity.STATE_NUM != 1 && SubListActivity.STATE_NUM<5) {
							SubListActivity.STATE_NUM = 1;//空闲
							manager.send(new SendStateData(SubListActivity.STATE_NUM));
							mAudioPlay.stopPlayer();
						}

					}else if (SocketUtil.byteToHexString(bb[1]).equals("cf")) {
						//开启服务广播
						Log.i(TAG, "onSocketReadResponse: Cfff");
						Log.i(TAG, "onSocketReadResponse: "+SubListActivity.STATE_NUM);
						if(SubListActivity.STATE_NUM==4){ //分站之间广播
							ctx.closeAnim();
						}
						if (mAudioCapture.isCaptureStarted()) {
							mAudioCapture.stopCapture();
							manager.send(new SendStopBroadData());
						}

						if(mediaPlayer.isPlaying()){
							mediaPlayer.pause();
							mediaPlayer.stop();
						}
						//获取本地广播实例。
						if(SubListActivity.STATE_NUM!=6){
							mAudioPlay.stopPlayer();
							mAudioPlay.startPlayer();
							SubListActivity.STATE_NUM = 6;//服务广播
							manager.send(new SendStateData(SubListActivity.STATE_NUM));
							localBroadcastManager.sendBroadcast(new Intent(BROADCAST_SERVER));//没有接收
						}

					}else if (SocketUtil.byteToHexString(bb[1]).equals("e1")) {
						//删除背景音乐文件
						if(musicList.size()!=0){
							for(String s:musicList){
								FileUtil.deletefile(s);
							}
							musicList.clear();
						}

					}else if (SocketUtil.byteToHexString(bb[1]).equals("e2")) {
						//音量调节

						int i = SocketUtil.byteToInt(bb[7]);
						Log.i(TAG, "onSocketReadResponse: E2E2E2E2   "+i);
						VolumeUtil.setStreamVolume(i);
					}else if (SocketUtil.byteToHexString(bb[1]).equals("c3")) {
						Log.i(TAG, "onSocketReadResponse: C333");
						//背景音乐
						if(!mMusicName.equals("")){
							FileUtil.saveDataToFile(bb,7,bb.length-10,mMusicName);//保存背景音乐
						}
					}else if (SocketUtil.byteToHexString(bb[1]).equals("c4")) {
						//服务广播
						Log.i(TAG, "onSocketReadResponse: C444");

						mAudioPlay.play(bb, 7, bb.length - 10);//播放

					} else if (SocketUtil.byteToHexString(bb[1]).equals("c5")) {
						Log.i(TAG, "onSocketReadResponse: C555");
						if(mediaPlayer.isPlaying()){
							mediaPlayer.pause();
							mediaPlayer.stop();
						}
						//分站广播
						if(SubListActivity.STATE_NUM<5){
							if(SubListActivity.STATE_NUM!=4){
								//setKeyPress(KeyEvent.KEYCODE_F4);
								//mAudioPlay.stopPlayer();
								//musicLength = 0;
								//musicByte = new byte[40960000];
								mAudioPlay.startPlayer();
								SubListActivity.STATE_NUM = 4;
								manager.send(new SendStateData(SubListActivity.STATE_NUM));
								localBroadcastManager.sendBroadcast(new Intent(BROADCAST_CLIENT));//没有接收处理
							}
							mAudioPlay.play(bb, 7, bb.length - 10);//播放分站广播;
						}
					} else if (SocketUtil.byteToHexString(bb[1]).equals("c8")) {
						//修改分站组
						Log.i(TAG, "onSocketReadResponse: C888");
						String numStr = String.valueOf(SocketUtil.byteToInt(bb[7]));
						String className = SocketUtil.unicode2String(SocketUtil.bytesToHexString(bb,
								9, bb.length - 4));
						boolean isHasClass = false;
						for (SubConf.SubgroupConf ss : sc.getSubgrouplist()) {
							if (ss.getNumber().equals(numStr)) {
								isHasClass = true;
								ss.setName(className);
								break;
							}
						}
						if (!isHasClass) {
							SubConf.SubgroupConf ss = new SubConf.SubgroupConf();
							ss.setName(className);
							ss.setNumber(numStr);
							ss.setSublist(new ArrayList<SubConf.SubgroupConf.SubListConf>());
							sc.getSubgrouplist().add(ss);
						}
						sc.notifyDataSetChange();


					} else if (SocketUtil.byteToHexString(bb[1]).equals("c9")) {
						//删除分站组
						Log.i(TAG, "onSocketReadResponse: C999");
						String numStr = String.valueOf(SocketUtil.byteToInt(bb[7]));
						for (SubConf.SubgroupConf ss : sc.getSubgrouplist()) {
							if (ss.getNumber().equals(numStr)) {
								sc.getSubgrouplist().remove(ss);
								break;
							}
						}
						sc.notifyDataSetChange();

					}
				}

			}
		});

		//调用通道进行连接
		manager.connect();

	}

	@Override
	public void deleteFile(SubListActivity ctx) {
		if(mediaPlayer!= null){
			mediaPlayer.pause();
			mediaPlayer.stop();
		}

		if(musicList.size()!=0){
			for(String s:musicList){
				Log.i(TAG, "deleteFile: ----------delete"+s);
				FileUtil.deletefile(s);
			}
			musicList.clear();
			mMusicName = "";
		}
	}


}
